<?php
/*
Make a request:
Parameters
	Pmax: maximum number of results
	Pstart_d, Pstart_h: Start date and time
	Pend_d, Pend_h: End date and time
	Poffset: offset from start
	Pxxxnn: column xxx constrainte number nn
*/

require( 'lib.php' );

// Check max lines
$max = min($dbmaxresults,intval($_POST['Pmax']));

// Set offset
$offset = intval($_POST['Poffset']);

// Build request
$select = array();
$wherec  = array();
$wherep = array();

// Parameters
foreach( $dbitem as $i ) {

	$col = $i['column'];

	// Request column content
	$select[] = $col . ' AS P'.$col;

	// Time interval
	if( $i['type'] == 'TIMESTAMP' ) {
		$timestamp = $col;
		$wherec[] = $col." BETWEEN STR_TO_DATE(?,'%Y-%m-%d %T') AND STR_TO_DATE(?,'%Y-%m-%d %T')";
		$wherep[] = $_POST['Pstart_d'] . " " . $_POST['Pstart_h'];
		$wherep[] = $_POST['Pend_d'] . " " . $_POST['Pend_h'];
	}
	
	// Constraintes
	for( $j=0; isset($_POST['P'.$col.$j]); $j++ ) {
		$param = $_POST['P'.$col.$j];
		$mode = substr($param,0,1);
		$param = substr($param, 1);
		// First character is:
		//	c from configuration
		//	= equality
		//	n inequality
		//	l like
		//	^ not like
		//	~ match
		//	! not match
		switch($mode) {
				
			case('c'):
				if( isset($i['list'][$param]['where']) ) {
					$wherec[] = $col . " " . $i['list'][$param]['where'];
				} else {
					print_r($i['list'][$param]['where']);
					die("Invalid value \"$param\" for $col");
				}
				break;
				
			case('='):
				$wherec[] = $col . "=?";
				$wherep[] = $param;
				break;
			
			case('n'):
				$wherec[] = $col . "!=?";
				$wherep[] = $param;
				break;
			
			case('l'):
				$wherec[] = $col . " LIKE ?";
				$wherep[] = "%$param%";
				break;
					
			case('^'):
				$wherec[] = $col . " NOT LIKE ?";
				$wherep[] = "%$param%";
				break;
					
			case('~'):
				$wherec[] = $col . " REGEXP ?";
				$wherep[] = $param;
				break;
					
			case('!'):
				$wherec[] = $col . " NOT REGEXP ?";
				$wherep[] = $param;
				break;
					
			default:
				die("Invalid type for $col");
			
		}
	}
}

// Build request
$sql = "SELECT ".implode(',',$select)." FROM $dbtable WHERE ".implode(' AND ', $wherec ). " ORDER BY $timestamp DESC LIMIT ".($max + 1)." OFFSET ".$offset;

// Connect to database
db();

// Run request
#print_r( $sql );
#print "<br/>\n";
#print_r( $wherep );
$stmt = $dbh->prepare( $sql );
$stmt->execute( $wherep );

print '{ "result": [';
print "\n";
$count = 0;
while( $r = $stmt->fetch(PDO::FETCH_ASSOC) ) {
	// Too much results
	if( $count >= $max ) {
		break;
	}
	// Skip comma before first record
	if( $count++ ) { print ",\n"; }
	print htmlspecialchars( json_encode($r), ENT_NOQUOTES );
}

// End of array
print ']';

// Debug SQL
print ', "sql": "'.rawurlencode($sql).'"';

// More result ?
#if( $count >= $max ) {
	print ', "more": '.($count>=$max ? 1 : 0);
#}

// End
print "}\n";
/*

*/	